﻿jQuery(function($) {
    $(document).ready(function() {
        $("#tab").tabs();
        $(".func").fmenu("grid");
        
        var branch = $("select[id$='ddlBranch']"),
			depart = $("select[id$='ddlDepart']"),
			job = $("select[id$='ddlJob']"),
			allFields = $([]).add(branch).add(depart).add(job),
			tips = $("#validateTips");
			
		var userId;
		var action; 
		var posId;
		
		var branchId;
		var departId;
		var jobId;
		var groupId;
			
        function updateTips(msg) {
            //tips.html(t).effect("highlight", {}, 1500);
            $("#validateTips").show();
            var err = "";
            for (i=0; i<msg.length; i++)
                err = err + "<li>" + msg[i] + "</li>";
            err = "<ul>" + err + "</ul>";
            tips.html(err).effect("highlight", {}, 1500);
        }
        
        function validform() {
            allFields.removeClass('ui-state-error');
            var bValid = true;
            
            var msg = new Array();

            if (branch.val() == "") {
                branch.addClass('ui-state-error');
                //updateTips('Chọn chi nhánh');
                msg.push("Chọn chi nhánh");
                bValid = bValid && false;
            }
            
            if (depart.val() == "") {
                depart.addClass('ui-state-error');
                //updateTips('Chọn phòng ban');
                msg.push("Chọn phòng ban");
                bValid = bValid && false;
            }
            
            if (job.val() == "") {
                job.addClass('ui-state-error');
                //updateTips('<b>Chọn chức vụ</b>');
                msg.push("Chọn chức vụ");
                bValid = bValid && false;
            }
            
            if (!bValid)
                updateTips(msg);

            return bValid;
        }
        
        $("#form").dialog({
            bgiframe: false,
            autoOpen: false,
            height: 300,
            width: 400,
            modal: true,
            draggable: true,
            resizable: true,
            buttons: {
                'Cập nhật':function(){
                    bValid = validform();

                    if (bValid) {
                        $("#validateTips").hide();
                        $("#update").hide();
                        $("#loading").show();
                        $("button").attr('disabled', 'disabled');

                        if (action == "add-sub" || action == "edit-sub")
                            insertPositionSub($(this));
                        else
                            insertPosition($(this));
                        //$(this).dialog('close');
                    }
                },
                'Thoát':function(){
                    $(this).dialog('close');
                }
            },
            open: function(event, ui) {
                allFields.removeClass('ui-state-error');
                $("#validateTips").html("");
                $("#validateTips").hide();
                $("#loading").hide();
                $("#update").show();
                $("button").attr('disabled', '');
                
                //$('#form').data('title.dialog', 'new title'); 
            }
            
        });
        
        function init()
        {
            branchId = '';
            departId = '';
            jobId = '';
            groupId = '';
        }
        
        function setPosition(obj)
        {
            $('#form').data('title.dialog', 'Phân bổ nhân viên');
            init();
            branch.val('');
            depart.val('');
            job.val('');
            
            userId = obj.attr("user");
            action = obj.attr("action");
                
            loadInfo();
            $("#form").dialog('open');
            
            if (action == "edit")
            {
                var items = obj.attr("item").split('|');
                branch.val(items[0]);
                depart.val(items[1]);
                job.val(items[2]);
                
                branchId = items[0];
                departId = items[1];
                jobId = items[2];
                groupId = items[3];
            }
            else if (action == "add-sub")
            {
                posId = "";
                $('#form').data('title.dialog', 'Phân bổ vị trí phụ');
            }
            else if (action == "edit-sub")
            {
                posId = obj.attr("id");
                $('#form').data('title.dialog', 'Phân bổ vị trí phụ');
                
                var items1 = obj.attr("item").split('|');
                branch.val(items1[0]);
                depart.val(items1[1]);
                job.val(items1[2]);
                
                branchId = items[0];
                departId = items[1];
                jobId = items[2];
                groupId = items[3];
            }
        }
        
        $(".position").click(function(){
            setPosition($(this));
        });
        
        $(".sub").click(function(){
            var isload = $(this).attr("isload");
            var user = $(this).attr("user");
            if (isload == "false")
            {
                var _url = "/Member/Webservice/GetPositionSub.aspx";
                var _data = "u=" + $(this).attr("user");
                $.ajax({
                    url: _url,
                    data: _data,
                    cache: false,
                    success: function(html){
                        var obj = $(html);
                        var html2 = obj.html();
                        if (html2 != "")
                        {
                            var obj2 = $(html2);
                            obj2.find(".position").bind('click', function(){
                                setPosition($(this));
                            });
                            
                            obj2.find(".del-sub").bind('click', function(){
                                delSub($(this));
                            });
                            $("td." + user).html(obj2);
                            $(".sub-" + user).attr("isload", "true");
                            $("td." + user).css("display", "");
                        }
                    },
                    error: function(){
                    }
                });
            }
            else
            {
                $("td." + user).toggle();
            }
        });
        
        function insertPosition(form)
        {
            var jsonStr = "{BranchId:'" + branch.val() + "',DepartId:'" + depart.val() + "',JobId:'" + job.val() + "',userId:'" + userId + "'}";
            var _url = "/Member/Webservice/MemberService.asmx/UpdatePosition";
            
            if (action == "add-sub")
            {
                _url = "/Member/Webservice/MemberService.asmx/UpdatePositionSub";
            }
            
            $.ajax({
                type: "POST",
                url: _url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonStr,
                success: function(msg) {
                    //$("#kq").html(msg.d);
                    form.dialog('close');
                    window.location = location.href;
                    return true;
                },
                error: function() {
                    return false;
                }
            });
        }
        
        function insertPositionSub(form)
        {
            var jsonStr = "{Id:'" + posId + "',BranchId:'" + branch.val() + "',DepartId:'" + depart.val() + "',JobId:'" + job.val() + "',userId:'" + userId + "'}";
            var _url = "/Member/Webservice/MemberService.asmx/UpdatePositionSub";
            
            $.ajax({
                type: "POST",
                url: _url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonStr,
                success: function(msg) {
                    //$("#kq").html(msg.d);
                    form.dialog('close');
                    window.location = location.href;
                    return true;
                },
                error: function() {
                    return false;
                }
            });
        }
        
        function loadInfo()
        {
            var jsonStr = "{userName:'" + userId + "'}";
            
            $.ajax({
                type: "POST",
                url: "/Member/Webservice/MemberService.asmx/UserInfo",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonStr,
                success: function(msg) {
                    $("#lblUser").text(msg.d[0]);
                    $("#lblFullName").text(msg.d[1]);
                    loadDepart();
                    //$("#form").dialog('open');
                    return true;
                },
                error: function() {
                    return false;
                }
            });
        }
        
        function delSub(obj)
        {
             var jsonStr = "{Id:'" + obj.attr("id") + "'}";
            
            $.ajax({
                type: "POST",
                url: "/Member/Webservice/MemberService.asmx/DeletePosition",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonStr,
                success: function(msg) {
                    window.location=location.href;
                    //$("#form").dialog('open');
                    return true;
                },
                error: function() {
                    return false;
                }
            });
        }
        
        /* xu ly load combobox */
        function loadDepart()
        {
            var _url = "/Admin/Hurman/Webservices/loadDepart.aspx";
            var _data = "b=" + branch.val();
            $.ajax({
                url: _url,
                data: _data,
                cache: false,
                success: function(html){
                    var obj = $(html);
                    $("#divDepart select").html(obj.find("select").html());
                    $("select[id$='ddlDepart']").val(departId);
                    loadJob();
                },
                error: function(){
                }
            });
        }
        
        function loadJob()
        {
            var _url = "/Admin/Hurman/Webservices/loadJob.aspx";
            var _data = "b=" + branch.val() + "&d=" + depart.val();
            $.ajax({
                url: _url,
                data: _data,
                cache: false,
                success: function(html){
                    var obj = $(html);
                    $("#divJob select").html(obj.find("select").html());
                    $("select[id$='ddlJob']").val(jobId);
                    loadGroup();
                },
                error: function(){
                }
            });
        }
        
        function loadGroup()
        {
            var _url = "/Admin/Hurman/Webservices/loadGroup.aspx";
            var _data = "b=" + branch.val() + "&d=" + depart.val() + "&j=" + job.val();
            $.ajax({
                url: _url,
                data: _data,
                cache: false,
                success: function(html){
                    var obj = $(html);
                    $("#divGroup select").html(obj.find("select").html());
                    $("select[id$='ddlGroup']").val(groupId);
                },
                error: function(){
                }
            });
        }
        
        $("select[id$='ddlBranch']").change(function(){
            loadDepart();
        });
        
        $("select[id$='ddlDepart']").change(function(){
            loadJob();
        });
        
        $("select[id$='ddlJob']").change(function(){
            loadGroup();
        });
    });
});